﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraVerticalGrid;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Sistem.Conversion
{
    public partial class Import : XForm
    {
        string TableName;
        int customerId;
        RepositoryItemComboBox riCols
        {
            get
            {
                RepositoryItemComboBox ri = new RepositoryItemComboBox();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.DropDownRows = 24;
                ri.Items.AddRange(col);
                return ri;
            }
        }

        BindingSource bs, bsO, bsP;
        DataTable dtData;
        DataTable dtPairs = new DataTable("Pairs");
        object[] col;

        public Import(string tableName, DataTable dataTable)
        {
            InitializeComponent();

            TableName = tableName;
            dtData = dataTable;
            dtData.TableName = "Data";
            TAM.DU4OrdersTableAdapter = new Datasets.MyDataTableAdapters.DU4OrdersTableAdapter();
            TAM.TexcommOrdersTableAdapter = new Datasets.MyDataTableAdapters.TexcommOrdersTableAdapter();
        }

        public Import(string tableName, DataTable dataTable, int custId)
        {
            InitializeComponent();
            customerId = custId;
            TableName = tableName;
            dtData = dataTable;
            dtData.TableName = "Data";
            TAM.OrdersTableAdapter = new Datasets.MyDataTableAdapters.OrdersTableAdapter();
        }

        private void Import_Load(object sender, EventArgs e)
        {
            int x = 0;
            if (TableName == "Orders")
                GetDetails("xCols", "GetCols2", customerId);
            else
                GetDetails("xCols", "GetCols", TableName);
            col = new object[ds.xCols.Rows.Count];
            foreach (MyData.xColsRow r in ds.xCols)
            {
                col[x] = r[0];
                x++;
            }

            DataTable dtBrand = Session.DataManager.ExecuteDataTableByQuery("select BrandId, Name from Brand where CustomerId = " + customerId + " and ISNULL(Deleted,0)=0");
            DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit riBrand = GetCustomGLE(dtBrand, "Name", "BrandId");

            ds.Tables.Add(dtData);
            bs = new BindingSource(ds, "Data");
            InitGridView(gridView1, bs);
            gridView1.BestFitColumns();

            foreach (DataColumn c in dtData.Columns)
                dtPairs.Columns.Add(c.ColumnName, typeof(string));

            ds.Tables.Add(dtPairs);
            bsP = new BindingSource(ds, "Pairs");
            vgc.DataSource = bsP;
            for (int i = 0; i < vgc.Rows.Count; i++)
                vgc.Rows[i].Properties.RowEdit = riCols;

            DataRow dr = dtPairs.NewRow();

            DataTable dtCaptionTR = Session.DataManager.ExecuteDataTableByQuery("select distinct CaptionTR from OrdersCol where CustomerId = " + customerId);
            DataTable dtExceldenGelen = new DataTable();
            dtExceldenGelen.Columns.Add("ValueToMatch");
            DataTable dx = new DataTable();
            foreach (DataColumn dc in dtPairs.Columns)
            {
                DataRow dr2 = dtExceldenGelen.NewRow();
                dr2["ValueToMatch"] = dc.ColumnName;
                dtExceldenGelen.Rows.Add(dr2);
            }

            if (TableName == "Orders")
                dx = Match(dtExceldenGelen, dtCaptionTR, 41);
            else
                dx = Match(dtPairs, TableName, 41);
            foreach (DataRow drMatch in dx.Rows)
                dr[drMatch["ValueToMatch"].ToString()] = drMatch["MatchedValue"];

            dtPairs.Rows.Add(dr);
            vgc.RecordCellStyle += vgc_RecordCellStyle;

            vgc.BestFit();

            bbiSave.Enabled = false;

            bsO = new BindingSource(ds, TableName);
            AddBsToList(bsO);

            gridView1.AddSummary();

        }

        void vgc_RecordCellStyle(object sender, DevExpress.XtraVerticalGrid.Events.GetCustomRowCellStyleEventArgs e)
        {
            VGridControl vGrid = sender as VGridControl;

            string caption = e.Row.Name.Replace("row", "").Replace(" ", "").Replace("_", "").Trim().ToLower();

            string sagHucre = vGrid.GetCellValue(e.Row, e.RecordIndex).ToStr().Replace(" ", "").Replace("_", "").Trim().ToLower();
            if (caption != sagHucre)
                e.Appearance.BackColor = Color.AntiqueWhite;
            //e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
            //e.Appearance.ForeColor = Color.SaddleBrown;
        }



        private DataTable Match(DataTable dtOriginalColumnBased, string InformationSchemaTableName, int MinScore)
        {
            DataTable dtOriginal = new DataTable();
            dtOriginal.Columns.Add("ValueToMatch", typeof(string));
            foreach (DataColumn dc in dtOriginalColumnBased.Columns)
            {
                DataRow dr = dtOriginal.NewRow();
                dr["ValueToMatch"] = dc.ColumnName;
                dtOriginal.Rows.Add(dr);
            }

            DataTable dtSource = Session.DataManager.ExecuteDataTable("GetMatchedColumns", InformationSchemaTableName);
            return Match(dtOriginal, dtSource, MinScore);
        }

        private DataTable Match(DataTable dtOriginal, DataTable dtSource, int MinScore)
        {
            dtOriginal.Columns[0].ColumnName = "ValueToMatch";
            dtSource.Columns[0].ColumnName = "SourceValue";

            string org = dtOriginal.Serialize();//XML.Serialize(dtOriginal, "OriginalTable", "Match");
            string source = dtSource.Serialize();//XML.Serialize(dtSource, "SourceTable", "Match");

            return Session.DataManager.ExecuteDataTable("MatchSimilar", org, source, MinScore);
        }

        public string Dupl = string.Empty;

        private void bbiSutun_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            List<string> ciftler = new List<string>();

            for (int i = 0; i < dtPairs.Columns.Count; i++)
            {
                string YeniDeger = dtPairs.Rows[0][i].ToString();
                if (YeniDeger == string.Empty)
                {
                    continue;
                }
                string cift = dtPairs.Columns[i].ColumnName;
                bool found = false;
                for (int j = i + 1; j < dtPairs.Columns.Count; j++)
                {
                    string SonrakiDeger = dtPairs.Rows[0][j].ToString();
                    if (YeniDeger == SonrakiDeger)
                    {
                        cift += "," + dtPairs.Columns[j].ColumnName;
                        found = true;
                    }
                }
                if (found)
                {
                    ciftler.Add(cift);
                }
            }

            foreach (string cift in ciftler)
            {

                string master = cift.Split(',')[0];
                string[] cols = cift.Replace(master + ",", "").Split(',');
                dtData.MergeColumns(master, cols);
            }

            foreach (DataColumn col in dtData.Columns)
            {
                object match = dtPairs.Rows[0][col.ColumnName];
                if (match != null)
                    if (match != DBNull.Value)
                        col.ColumnName = match.ToString();
            }

            gridView1.PopulateColumns();
            gridView1.BestFitColumns();
            bbiSave.Enabled = true;
        }

        private void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            string customerName = customerId != 0 ? AppSession.Lookups.V_Customer.FindByCustomerId(customerId).Name : "";

            switch (TableName)
            {
                case "DU4Orders":
                    DataTable dd = ExecuteDataTable("CheckDU4Orders", dtData.Serialize());

                    if (dd.Rows.Count == 0)
                    {
                        Dupl = string.Empty;
                        ds.DU4Orders.Clear();

                        foreach (DataRow drData in dtData.Rows)
                        {
                            DataRow r = ds.DU4Orders.NewRow();

                            for (int i = 0; i < dtData.Columns.Count; i++)
                            {
                                string colName = dtData.Columns[i].ColumnName;  // Caption;
                                if (ds.DU4Orders.Columns.Contains(colName))
                                    if (drData[colName].ToString() != string.Empty)
                                        r[colName] = drData[colName];
                            }
                            ds.DU4Orders.AddDU4OrdersRow((MyData.DU4OrdersRow)r);
                        }
                    }
                    else
                    {
                        Dupl = "PA\tDispoNo\tArticle" + Environment.NewLine + Environment.NewLine;

                        foreach (DataRow dr in dd.Rows)
                            Dupl += dr["PA"].ToString() + "\t" + dr["DispoNo"].ToString() + "\t" + dr["Article"].ToString() + Environment.NewLine;
                    }

                    string str = ds.DU4Orders.SerializeChanges();
                    ExecuteNonQuery("InsDu4Orders", str);
                    break;

                case "Orders":
                    ds.Orders.Clear();

                    ds.DagilimC.Merge(ExecuteDataTable("GetDagilimC", customerId));
                    if (customerId == 42 || customerId == 17 || customerId == 323 || customerId == 306 || customerId == 69 || customerId == 241 || customerId == 73 || customerId == 102)
                    {
                        foreach (DataRow drData in dtData.Rows)
                        {
                            int DagilimId = 0;
                            DataRow r = ds.Orders.NewRow();

                            switch (drData["BD"].ToString().ToLower())
                            {
                                case "tek": DagilimId = 7; break;
                                case "harf": DagilimId = 10; break;
                                case "bayan": DagilimId = 12; break;
                                case "çift": DagilimId = 32; break;
                                case "22": DagilimId = 22; break;
                                case "inçli": DagilimId = 36; break;
                                case "kol5": DagilimId = 25; break;
                                case "kol7": DagilimId = 17; break;
                                case "kol5ve7": DagilimId = 37; break;
                                default: throw new ApplicationException("Dağılım tipi eksik/hatalı satırlar var. Lütfen düzelttikten sonra tekrar deneyin.");
                            }

                            r["DagilimId"] = DagilimId;
                            MyData.DagilimCRow drow = ds.DagilimC.FindByDagilimIdCustomerId(DagilimId, customerId);

                            for (int i = 1; i <= 28; i++)
                                if (dtData.Columns.Contains(drow[String.Format("A{0:00}", i)].ToString()))
                                    r[String.Format("A{0:00}", i)] = drData[drow[String.Format("A{0:00}", i)].ToString()];

                            DataTable dtRealColName = Session.DataManager.ExecuteDataTableByQuery("select distinct Col, CaptionTR from OrdersCol where CustomerId = " + customerId);
                            foreach (DataColumn dc in dtData.Columns)
                                foreach (DataRow dr in dtRealColName.Rows)
                                    if (dc.ColumnName == dr["CaptionTR"].ToString())
                                        dtData.Columns[dc.ColumnName].ColumnName = dr["Col"].ToString();

                            for (int i = 0; i < dtData.Columns.Count; i++)
                            {
                                string colName = dtData.Columns[i].ColumnName;  // Caption;
                                if (ds.Orders.Columns.Contains(colName))
                                    if (drData[colName].ToString() != string.Empty)
                                        r[colName] = drData[colName];
                            }
                            ds.Orders.AddOrdersRow((MyData.OrdersRow)r);
                        }

                        using (SiparisGir apo = new SiparisGir())
                            if (apo.ShowDialog() == DialogResult.OK)
                            {
                                foreach (DataRow drSip in ds.Orders.Rows)
                                {
                                    drSip["BrandId"] = apo.BrandId;
                                    drSip["SezonId"] = apo.SezonId;
                                    drSip["OrderRef"] = apo.OrderRef;
                    }
                            }
                            else
                                return;
                    }
                    break;
                    
                case "TexcommOrders":
                    ds.TexcommOrders.Clear();
                    ds.TexcommOrders.Columns.Add("DosyaAdi", typeof(string));
                    ds.TexcommOrders.Columns.Add("CLIENTE", typeof(int));
                    ds.TexcommOrders.Columns.Add("ORDINE", typeof(int));
                    for (int i = 1; i < 29; i++)
                        ds.TexcommOrders.Columns.Add(string.Format("A{0:00}", i), typeof(int));

                    ds.DagilimC.Merge(ExecuteDataTable("GetDagilimC", 68));
                    foreach (DataRow drData in dtData.Rows)
                    {
                        int DagilimId = 0;
                        DataRow r = ds.TexcommOrders.NewRow();
                        int duzToplam = 0;
                        int SMLToplam = 0;
                        int RomenToplam = 0;

                        for (int i = 32; i < 56; i++)
                        {
                            if (i == 33)
                                continue;
                            
                            duzToplam += drData[i.ToString()].ToInt();
                        }

                        foreach (string label in "XXS;XS;S;M;L;XL;XXL;XXXL;4XL;5XL;6XL".Split(';'))
                            SMLToplam += drData[label.ToString()].ToInt();

                        foreach (string label in "I;II;III;IV;V;VI;VII;VIII;IX;X".Split(';'))
                            RomenToplam += drData[label.ToString()].ToInt();

                        int exception = 0;
                        if (duzToplam > 0)
                        {
                            DagilimId = 7;
                            exception++;
                        }
                        if (SMLToplam > 0)
                        {
                            DagilimId = 10;
                            exception++;
                        }
                        if (RomenToplam > 0)
                        {
                            DagilimId = 6;
                            exception++;
                        }

                        if (exception > 1)
                        {
                            throw new ApplicationException("Aynı siparişte, birden fazla dağılıma adet girilmiş. ");
                        }


                        r["DagilimId"] = DagilimId;
                        MyData.DagilimCRow drow = ds.DagilimC.FindByDagilimIdCustomerId(DagilimId, 68);

                        for (int i = 1; i <= 28; i++)
                            if (dtData.Columns.Contains(drow[String.Format("A{0:00}", i)].ToString()))
                                r[String.Format("A{0:00}", i)] = drData[drow[String.Format("A{0:00}", i)].ToString()];

                        for (int i = 0; i < dtData.Columns.Count; i++)
                        {
                            string colName = dtData.Columns[i].ColumnName;  // Caption;

                            if (colName == "DosyaAdi" || colName == "CLIENTE" || colName == "ORDINE")
                            {
                                r[colName] = drData[colName];
                            }
                            else if (ds.TexcommOrders.Columns.Contains(colName))
                                if (drData[colName].ToString() != string.Empty)
                                    r[colName] = drData[colName];
                        }
                        ds.TexcommOrders.AddTexcommOrdersRow((MyData.TexcommOrdersRow)r);
                    }
                    using (SiparisGir apo = new SiparisGir())
                        if (apo.ShowDialog() == DialogResult.OK)
                        {
                            foreach (DataRow drSip in ds.TexcommOrders.Rows)
                            {
                                drSip["BrandId"] = apo.BrandId;
                                drSip["SezonId"] = apo.SezonId;
                                drSip["OrderRef"] = apo.OrderRef;
                            }
                        }
                        else
                            return;
                    break;
                     
            }


            if (TableName == "TexcommOrders")
            {
                string str = ds.TexcommOrders.SerializeChanges();
                ExecuteNonQuery("InsTexcommOrders", str);
            }
            else
            if (TableName == "Orders")
            {
                string str = ds.Orders.SerializeChanges();
                ExecuteNonQuery("InsGeneralOrders", str);

            }

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        
        }
    }
}